package com.hsnn.medstgmini.trading.pur.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.form.DicAreaForm;
import com.hsnn.medstgmini.base.dict.service.DicAreaManager;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.pur.model.OrderPackStatus;
import com.hsnn.medstgmini.trading.pur.model.PurOrderLogisticsOld;
import com.hsnn.medstgmini.trading.pur.model.form.DispatchInfo;
import com.hsnn.medstgmini.trading.pur.model.form.OrderDetail;
import com.hsnn.medstgmini.trading.pur.model.form.OrderPack;
import com.hsnn.medstgmini.trading.pur.model.form.OrderPackage;
import com.hsnn.medstgmini.trading.pur.model.form.PurOrderInfoForm;
import com.hsnn.medstgmini.trading.pur.service.OrderConfirmManager;
import com.hsnn.medstgmini.trading.pur.service.PurOrderInfoManager;
import com.hsnn.medstgmini.util.DbUtil;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;
import com.hsnn.medstgmini.validator.ValidatorUtil;

/**
 * @category 中心端查看订单明细
 * @author 应晓川
 * @date 2015年7月9日
 */
@Controller
@RequestMapping("/purOrderInfo")
public class PurOrderInfoController {
	
	private static final Logger log = Logger.getLogger(PurOrderInfoController.class);
	
	@Autowired
	private PurOrderInfoManager purOrderInfoManager;
	
	@Autowired
	private OrderConfirmManager orderConfirmManager;
	
	@Autowired
	private DicAreaManager dicAreaManager;
	
	@Autowired
	private HttpServletRequest request;

	@Autowired
	private HttpSession session;
	
	@Value("#{sysProp['system.province']}")
	private String sysProvince;
	
	@Value("#{sysProp['system.isHisRecordAmount']}")
	private boolean isHisRecordAmount;
	
	/**
	 * @category 获取当前登陆人信息
	 * @date 2015年6月14日
	 * @return
	 */
	public SysUser getUser() {
		return (SysUser) session.getAttribute(Constants.USERINFO);
	}
	
	/**
	 * @category 跳转至订单明细页面[中心端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/toOrderInfo")
	public String toOrderInfo() {
		DicAreaForm area = dicAreaManager.getDicAreaById(sysProvince);
		request.setAttribute("area", area);
		request.setAttribute("sysAreaId", sysProvince);
		return "/trading/pur/purOrderInfo";
	}
	
	/**
	 * @category 获取订单数据[中心端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/getOrdersDetailList")
	@ResponseBody
	public Pagination getOrdersDetailList(OrderPackage orderPackage) {
		log.info("enter getOrdersDetailList method");
		Pagination page = new Pagination(request);
		try {
			page.setForm(orderPackage);
			page = purOrderInfoManager.getOrdersDetailList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	
	/**
	 * @category 跳转至订单明细页面[生产企业端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/toOrderInfoByProComp")
	public String toOrderInfoByProComp() {
		DicAreaForm area = dicAreaManager.getDicAreaById(sysProvince);
		request.setAttribute("area", area);
		request.setAttribute("sysAreaId", sysProvince);
		return "/trading/pur/purOrderInfoByProComp";
	}
	
	/**
	 * @category 获取订单数据[生产企业端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/getOrdersDetailListByProComp")
	@ResponseBody
	public Pagination getOrdersDetailListByProComp() {
		log.info("enter getOrdersDetailListByProComp method");
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String prodCompcode = ((StdCompinfo )user.getInfo()).getCompCode();
		try {
			DbUtil.jsonToMap(request, page);
			page.getConditions().put("prodCompcode", prodCompcode);
			page = purOrderInfoManager.getOrdersDetailListByProComp(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * @category 跳转至订单明细页面[配送企业端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/toOrderInfoByComp")
	public String toOrderInfoByComp() {
		DicAreaForm area = dicAreaManager.getDicAreaById(sysProvince);
		request.setAttribute("area", area);
		request.setAttribute("sysAreaId", sysProvince);
		return "/trading/pur/purOrderInfoByComp";
	}
	
	/**
	 * @category 获取订单数据[配送企业端]
	 * @date 2015年7月9日
	 * @return
	 */
	@RequestMapping("/getOrderListByComp")
	@ResponseBody
	public Pagination getOrderListByComp(OrderPackage orderPackage) {
		log.info("[配送企业端]获取订单数据："+orderPackage);
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
		//	orderPackage.setOrderStatus(OrderPackStatus.submit.getKey());
			//	获取配送企业code
			StdCompinfo comp = user.getInfo();
			orderPackage.setDelCompCode(comp.getCompCode());
			page.setForm(orderPackage);
			page = purOrderInfoManager.getOrdersDetailListByComp(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	/**
	 * @category 进入订单详细列表页面
	 * @date 2015年7月13日
	 * @return
	 */
	@RequestMapping("/toOrderDetailByComp")
	public String toOrderDetailByComp(Model model, String orderPackId) {
		Map<String, Object> map = orderConfirmManager.getOrderPackageById(orderPackId);
		model.addAttribute("orderPackId", orderPackId);
		model.addAttribute("orderPack", map);
		return "/trading/pur/orderDetailByComp";
	}

	/**
	 * @category 查询订单详细列表
	 * @date 2015年7月13日
	 * @param orderPackage
	 * @return
	 */
	@RequestMapping("/getOrderDetailByComp")
	@ResponseBody
	public Pagination getOrderDetailByComp(OrderPackage orderPackage) {
		log.info("[配送企业]查询订单详细列表："+orderPackage);
		Pagination page = new Pagination(request);
		try {
			orderConfirmManager.getOrderConfirmDetailDel(orderPackage, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	/**
	 * @category 获取订单配送信息
	 * @date 2015年11月30日
	 * @param orderPackage
	 * @return
	 */
	@RequestMapping("/getOrderDelList")
	@ResponseBody
	public Pagination getOrderDelList(OrderPackage orderPackage) {
		log.info("[配送企业]获取订单配送信息："+orderPackage);
		Pagination page = new Pagination(request);
		try {
			orderConfirmManager.getOrderDelList(orderPackage, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 跳向订单信息页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午9:49:56
	 *@return
	 */
	@RequestMapping("/toHospOderInfo")
	public String toHospOderInfo(){
		return "/trading/pur/hospOrder";
	}
	/**
	 * 
	 *@category 获取订单信息列表数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午10:10:41
	 *@return
	 */
	@RequestMapping("/getHospOderInfoDataList")
	@ResponseBody
	public Pagination getHospOderInfoDataList(OrderPackage orderPackage){
			log.info("[医疗机构]获取订单信息列表数据:"+orderPackage);
			Pagination page = new Pagination(request);
			try {
				HospInfo hosp = getUser().getInfo();
				orderPackage.setHospCode(hosp.getHospCode());
				page.setForm(orderPackage);
				page = purOrderInfoManager.getHospOderInfoDataList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
			}
			return page;
	}
	
	/**
	 * 
	 *@category 跳向订单信息详情页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午9:49:56
	 *@return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toHospOderInfoDateil")
	public String toHospOderInfoDateil() throws UnsupportedEncodingException{
		request.setAttribute("orderPackName", request.getParameter("orderPackId"));
		request.setAttribute("delCompName", URLDecoder.decode(request.getParameter("delCompName"), "utf-8"));
		return "/trading/pur/hospOrderDateil";
	}
	/**
	 * 
	 *@category 获取订单信息详情列表数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午10:10:41
	 *@return
	 */
	@RequestMapping("/getHospOderInfoDetailDataList")
	@ResponseBody
	public Pagination getHospOderInfoDetailDataList(PurOrderInfoForm form){
		log.info("[医疗机构]获取订单信息详情列表数据:"+form);
		Pagination page = new Pagination(request);
		page.setForm(form);
		page = purOrderInfoManager.getHospOderInfoDetailDataList(page);
		return page;
	}
	
	/**
	 *@category 跳向订单明细页面[医疗机构]
	 *@author 应晓川
	 *@date 2015年7月13日 
	 *@return
	 */
	@RequestMapping("/toOrderInfoByHosp")
	public String toOrderInfoByHosp(){
		return "/trading/pur/purOrderInfoByHosp";
	}
	
	/**
	 * @category 获取订单明细数据[医疗机构]
	 * @author 应晓川
	 * @date 2015年7月13日
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getOrderInfoByHosp")
	@ResponseBody
	public Pagination getOrderInfoByHosp() {
		log.info("enter getOrderInfoByHosp method");
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0].replace("+", "");
				page.getConditions().put(paramName, paramValue);
			}
		}
		//获取医疗机构的身份
		page.getConditions().put("hospId", ((HospInfo)user.getInfo()).getHospId());
		try {
			page = purOrderInfoManager.getOrderInfoByHosp(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
	/**
	 * 
	 *@category 跳向物流信息页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 下午2:08:16
	 *@return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toOrderLogistics")
	public String toOrderLogistics() throws UnsupportedEncodingException{
		Pagination page = new Pagination();
		page.getConditions().put("orderPackId", request.getParameter("orderPackId"));
		String delCompName = request.getParameter("delCompName");
		page = purOrderInfoManager.getOrderLogisticsData(page);
		request.setAttribute("form", page.getForm());
		request.setAttribute("rows", page.getRows());
		if (StringUtils.isNotBlank(delCompName)){
			request.setAttribute("delCompName", new String(delCompName.getBytes("ISO8859-1"),"utf-8"));
		}
		return "/trading/pur/deliverDetail";
	}
	/**
	 * 
	 *@category 根据包号跳向物流信息页面（医疗机构）
	 *@author 徐国鹏
	 *@date 2015年8月7日 下午14:08:16
	 *@return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toOrderLogisticsOld")
	public String toOrderLogisticsOld() throws UnsupportedEncodingException{
		Pagination page = new Pagination();
		page.getConditions().put("orderPackId", request.getParameter("orderPackId"));
		String delCompName = request.getParameter("delCompName");
		page = purOrderInfoManager.getOrderLogisticsDataOld(page);
		request.setAttribute("form", page.getForm());
		request.setAttribute("rows", page.getRows());
		if (StringUtils.isNotBlank(delCompName)){
			request.setAttribute("delCompName", new String(delCompName.getBytes("ISO8859-1"),"utf-8"));
		}
		return "/trading/pur/deliverDetailOld";
	}
	/**
	 * 
	 *@category 跳向医疗机构确认收货页面
	 *@author 邱磊
	 *@date 2015年7月13日 下午2:17:14
	 *@return
	 */
	@RequestMapping("/toConfirmRecp")
	public String toConfirmRecp(){
		return "/trading/pur/confirmRecp";
	}
	/**
	 * 
	 *@category 获取医疗机构确认收货页面数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月13日 下午2:19:02
	 *@param form
	 *@return
	 */
	@RequestMapping("/getConfirmRecpDataList")
	@ResponseBody
	public Pagination getConfirmRecpDataList(PurOrderInfoForm form){
		log.info("[医疗机构]获取医疗机构确认收货页面数据:"+form);
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		form.setHospCode(hospCode);
		form.setMain(user.getMain());
		form.setSubmitUser(user.getId());
		page.setForm(form);
		page = purOrderInfoManager.getConfirmRecpDataList(page);
		return page;
	}
	
	/**
	 * @category 获取医疗机构确认收货订单明细页面数据（医疗机构）
	 * @author 韩守松
	 * @date   2015年11月29日
	 * @param  @param form
	 * @param  @return
	 */
	@RequestMapping("/getConfirmRecpOrderDataList")
	@ResponseBody
	public Pagination getConfirmRecpOrderDataList(PurOrderInfoForm form){
		log.info("[医疗机构]获取医疗机构确认收货订单明细页面数据:"+form);
		Pagination page = new Pagination(request);
		page.setForm(form);
		page = purOrderInfoManager.getConfirmRecpOrderDataList(page);
		return page;
	}
	/**
	 * 
	 *@category 跳向确认收货详情页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月13日 下午2:31:11
	 *@return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toConfirmRecpDetail")
	public String toConfirmRecpDetail() throws UnsupportedEncodingException{
		SysUser user = (SysUser) session.getAttribute(Constants.USERINFO);
		request.setAttribute("userName", user.getName());
		request.setAttribute("delCompName", new String(request.getParameter("delCompName").getBytes("ISO8859-1"),"utf-8"));
		return "/trading/pur/orderGetDetail";
	}
	/**
	 * 
	 *@category 获取确认收货详情页面列表数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月13日 下午2:56:16
	 *@return
	 */
	@RequestMapping("/getConfirmRecpDetailDataList")
	@ResponseBody
	public Pagination getConfirmRecpDetailDataList(PurOrderInfoForm form){
		log.info("[医疗机构]获取医疗机构确认收货订单明细页面数据:"+form);
		Pagination page = new Pagination(request);
		try {
			page.setForm(form);
			page.getConditions().put("orderPackId", request.getParameter("orderPackId"));
			page = purOrderInfoManager.getConfirmRecpDetailDataList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
		
		
	}
	

	
	/**
	 * 
	 *@category 确认收货按钮操作（医疗机构）
	 *@author 韩守松
	 *@date 2015年12月15日 
	 *@return
	 */
	@RequestMapping("/confirmRecp")
	@ResponseBody
	public Pagination confirmRecp(OrderPack orderPack){
		log.info("[医疗机构]确认收货按钮操作:"+orderPack);
		Pagination page = new Pagination(request);
		
		if (null != orderPack.getOrderDetailList()) {
			List<OrderDetail> list = orderPack.getOrderDetailList();//获取页面传来的所有订单明细号
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if(list.size()>0){
				List<PurOrderInfoForm> orderFormList = new ArrayList<PurOrderInfoForm>();
				for(int i = 0;i<list.size();i++){
					List<DispatchInfo>  disList =  list.get(i).getDispatchInfoList();//获取每个订单明细号下的配送信息（多个批次号）
					Map<String, Integer> delInfoMap = purOrderInfoManager.getDelInfoList(disList);
					if(disList.size() > 0){
						List<PurOrderInfoForm> orderFormTList = new ArrayList<PurOrderInfoForm>();
						PurOrderInfoForm orderform = new PurOrderInfoForm();
						for(int j = 0;j<disList.size();j++){
							PurOrderInfoForm orderForm = new PurOrderInfoForm();
							DispatchInfo form = disList.get(j);//得到每个配送明细信息
							if (!ValidatorUtil.validatePositiveInteger(form.getRecpCount().toString())){
								page.setSuccess(false);
								page.setMsg("请正确填写到货数量！");
								return page;
							}
							if (ParseNumber.toInteger(form.getRecpCount().toString()) > delInfoMap.get(form.getDelDetailId())){
								page.setSuccess(false);
								page.setMsg("到货数量不能大于配送数量！");
								return page;
							}
							orderForm.setRecpUser(user.getId());
							orderForm.setStoreUser(user.getName());
							orderForm.setApproveCode(form.getApproveCode());
							orderForm.setRecpCount(form.getRecpCount().toString());
							orderForm.setDelDetailId(form.getDelDetailId());
							orderForm.setOrderCode(list.get(i).getOrderCode());
							orderForm.setOrderPackId(orderPack.getOrderPackId());
							orderFormTList.add(j,orderForm);//封装订单明细信息
						}
						orderform.setOrderDetailInfoList(orderFormTList);
						orderFormList.add(i,orderform);
					}
				}
				try {
					purOrderInfoManager.confirmRecp(orderFormList);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}
	/**
	 * 
	 *@category 未到货功能操作（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月13日 下午5:31:49
	 *@param array
	 *@param storeUser
	 *@return
	 */
	@RequestMapping("/notArrived")
	@ResponseBody
	public Pagination notArrived(OrderPack orderPack){
		log.info("[医疗机构]未到货功能操作:"+orderPack);
		Pagination page = new Pagination(request);
		if (orderPack.getOrderDetailList() != null && !"".equals(orderPack.getOrderDetailList())) {
			List<OrderDetail> list = orderPack.getOrderDetailList();
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if(list.size()>0){
				List<PurOrderInfoForm> orderFormList = new ArrayList<PurOrderInfoForm>();
				PurOrderInfoForm orderform = new PurOrderInfoForm();
				for(int i = 0;i<list.size();i++){
					List<DispatchInfo>  disList =  list.get(i).getDispatchInfoList();
					if(disList.size() > 0){
						List<PurOrderInfoForm> orderFormTList = new ArrayList<PurOrderInfoForm>();
						for(int j = 0;j<disList.size();j++){
							PurOrderInfoForm orderForm = new PurOrderInfoForm();
							DispatchInfo form = disList.get(j);
							orderForm.setRecpUser(user.getId());
							orderForm.setStoreUser(user.getName());
							orderForm.setApproveCode(form.getApproveCode());
							orderForm.setRecpCount(form.getRecpCount().toString());
							orderForm.setDelDetailId(form.getDelDetailId());
							orderForm.setOrderCode(list.get(i).getOrderCode());
							orderForm.setOrderPackId(orderPack.getOrderPackId());
							orderFormTList.add(j,orderForm);
						}
						orderform.setOrderDetailInfoList(orderFormTList);
						orderFormList.add(i,orderform);
					}
				}
				try {
					purOrderInfoManager.notArrived(orderFormList);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}
	/**
	 * 
	 *@category 跳向到货汇总页面（医疗机构）
	 *@author 韩守松
	 *@date 2015年11月30日 
	 *@return
	 */
	@RequestMapping("/toArrivedDrug")
	public String toArrivedDrug(){
		return "/trading/pur/confirmRecpListDetail";
	}
	/**
	 * 
	 *@category 获取到货汇总列表（医疗机构）
	 *@author 韩守松
	 *@date 2015年11月30日 
	 *@return
	 */
	@RequestMapping("/getArrivedDrug")
	@ResponseBody
	public Pagination getArrivedDrug(PurOrderInfoForm form){
		log.info("[医疗机构]获取到货汇总列表:"+form);
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		form.setHospCode(hospCode);
		form.setMain(user.getMain());
		form.setSubmitUser(user.getId());
		page.setForm(form);
		page = purOrderInfoManager.getArrivedDrug(page);
		return page;
	}
	
	/**
	 * 
	 *@category 整包确认收货（医疗机构操作，所有到货数量就是配送数量）
	 *@author 邱磊
	 *@date 2015年7月14日 上午9:22:13
	 *@return
	 */
	@RequestMapping("/confirmByPack")
	@ResponseBody
	public Pagination confirmByPack(String storeUser,String orderPackId){
		Pagination page = new Pagination(request);
		if (null == storeUser || "".equals(storeUser)){
			SysUser user = (SysUser) session.getAttribute(Constants.USERINFO);
			storeUser = user.getName();
		}
		page.getConditions().put("storeUser", storeUser);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		page.getConditions().put("recpUser", user.getId());
		page.getConditions().put("orderPackId", orderPackId);
		try {
			purOrderInfoManager.confirmByPack(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("操作失败，请联系管理员！");
			return page;
		}
		return page;
	}
	@RequestMapping("/multiConfirmByPack")
	@ResponseBody
	public Pagination multiConfirmByPack(String array){
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PurOrderInfoForm>>() {
			}.getType();
			List<PurOrderInfoForm> list = gson.fromJson(array, type);
			SysUser user = (SysUser) request.getSession().getAttribute(
					Constants.USERINFO);
			page.getConditions().put("storeUser", user.getName());
			page.getConditions().put("recpUser", user.getId());
			if (list != null && !list.isEmpty()) {
				String str ="";
				for (PurOrderInfoForm form : list) {
					 str += form.getOrderPackId()+",";
				}
				page.getConditions().put("orderPackIdList",str);
				try {
					purOrderInfoManager.confirmByPack(page);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("请求出错！");
					return page;
				}
			}
		} else {
			page.setSuccess(false);
			page.setMsg("请选择操作的数据！");
			return page;
		}
		return page;
	}
	/**
	 * 
	 *@category 整包未到货操作（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月14日 上午10:15:18
	 *@param storeUser
	 *@param orderPackId
	 *@return
	 */
	@RequestMapping("/noArrivedByPack")
	@ResponseBody
	public Pagination noArrivedByPack(String orderPackId){
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		page.getConditions().put("recpUser", user.getId());
		page.getConditions().put("orderPackId", orderPackId);
		try {
			purOrderInfoManager.noArrivedByPack(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("操作失败，请联系管理员！");
			return page;
		}
		return page;
	}
	@RequestMapping("/multiNoArrivedByPack")
	@ResponseBody
	public Pagination multiNoArrivedByPack(String array){
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PurOrderInfoForm>>() {
			}.getType();
			List<PurOrderInfoForm> list = gson.fromJson(array, type);
			SysUser user = (SysUser) request.getSession().getAttribute(
					Constants.USERINFO);
			page.getConditions().put("storeUser", user.getName());
			page.getConditions().put("recpUser", user.getId());
			if (list != null && !list.isEmpty()) {
				String str ="";
				for (PurOrderInfoForm form : list) {
					 str += form.getOrderPackId()+",";
				}
				page.getConditions().put("orderPackIdList",str);
				try {
					purOrderInfoManager.noArrivedByPack(page);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("请求出错！");
					return page;
				}
			}
		} else {
			page.setSuccess(false);
			page.setMsg("操作失败，请联系管理员！");
			return page;
		}
		return page;
	}
	/**
	 * 
	 *@category 根据订单明细ID查询物流信息
	 *@author 邱磊
	 *@date 2015年7月14日 上午10:50:08
	 *@return
	 */
	@RequestMapping("/toOrderLogisticsById")
	public String toDeliverDetailById(){
		Pagination page = new Pagination();
		page.getConditions().put("orderId", request.getParameter("orderId"));
		page = purOrderInfoManager.toDeliverDetailById(page);
		request.setAttribute("form", page.getForm());
		request.setAttribute("rows", page.getRows());
		return "/trading/pur/deliverDetailById";
	}
	/**
	 * 
	 *@category 根据订单明细ID查询物流信息
	 *@author 徐国鹏
	 *@date 2015年8月7日 下午14:50:08
	 *@return
	 */
	@RequestMapping("/toOrderLogisticsByIdOld")
	public String toDeliverDetailByIdOld(){
		Pagination page = new Pagination();
		page.getConditions().put("orderId", request.getParameter("orderId"));
		page = purOrderInfoManager.toDeliverDetailByIdOld(page);
		request.setAttribute("form", page.getForm());
		request.setAttribute("rows", page.getRows());
		return "/trading/pur/deliverDetailById";
	}
	/**
	 * 
	 *@category 跳向未评价订单评价页面
	 *@author 邱磊
	 *@date 2015年7月19日 上午11:39:55
	 *@return
	 */
	@RequestMapping("/toUnReviewsList")
	public String toUnReviewsList(){
		return "/trading/pur/unReviewsList";
	}
	/**
	 * 
	 *@category 获取未评价订单列表
	 *@author 邱磊
	 *@date 2015年7月19日 下午2:03:07
	 *@param form
	 *@return
	 */
	@RequestMapping("/getUnReviewsDataList")
	@ResponseBody
	public Pagination getUnReviewsDataList(PurOrderInfoForm form){
		Pagination page = new Pagination(request);
		page.setForm(form);
		return purOrderInfoManager.getUnReviewsDataList(page);
	}
	/**
	 * 
	 *@category 跳向评价页面
	 *@author 邱磊
	 *@date 2015年7月19日 下午8:39:51
	 *@return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toReviews")
	public String toReviews(String orderPackId) throws UnsupportedEncodingException{
		PurOrderInfoForm info = purOrderInfoManager.getLogisticsInfo(orderPackId);
		request.setAttribute("info", info);
		String delCompName = request.getParameter("delCompName");
		if (StringUtils.isNotBlank(delCompName)){
			request.setAttribute("delCompName", new String(delCompName.getBytes("ISO8859-1"),"utf-8"));
		}
		
		return "/trading/pur/reviews";
	}
	@RequestMapping("/saveReviews")
	@ResponseBody
	public Pagination saveReviews(PurOrderInfoForm form){
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		form.setGradeUser(user.getId());
		page.setForm(form);
		try {
			purOrderInfoManager.saveReviews(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("操作失败请联系管理员！");
			return page;
		}
		return page;
	}
	/**
	 * 
	 *@category 跳向已评价列表页面
	 *@author 邱磊
	 *@date 2015年7月20日 下午5:09:51
	 *@return
	 */
	@RequestMapping("/toReviewsList")
	public String toReviewsList(){
		return "/trading/pur/reviewsList";
	}
	@RequestMapping("/getReviewsDataList")
	@ResponseBody
	public Pagination getReviewsDataList(PurOrderInfoForm form){
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		form.setSubmitUser(user.getId());
		page.setForm(form);
		return purOrderInfoManager.getReviewsDataList(page);
	}
	/**
	 * @category 跳向已评价详情页面
	 * @Auther 徐国鹏
	 * @date 2015年8月4日 下午3:01:27
	 * @return String
	 */
	@RequestMapping("/toReviewsListDetail")
	public String toReviewsListDetail(String interflowId){
		PurOrderLogisticsOld data = purOrderInfoManager.getAoginfoById(interflowId);
		request.setAttribute("info", data);
		return "/trading/pur/reviewsListDetail";
	}
	@RequestMapping("/getReviewsDataListDetail")
	@ResponseBody
	public Pagination getReviewsDataListDetail(PurOrderInfoForm form){
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		form.setSubmitUser(user.getId());
		page.setForm(form);
		return purOrderInfoManager.getReviewsDataListDetail(page);
	}
	
	
	
	
	/**
	 * @category 完成订单查看（医疗机构端）
	 * @Auther 韩守松
	 * @date 2015年11月30日 
	 * @return String
	 */
	@RequestMapping("/toHospOderInfoOld")
	public String toHospOderInfoOld(){
		return "/trading/pur/hospOrderOld";
	}
	
	/**
	 * @category 获取完成订单数据
	 * @author 韩守松
	 * @date   2015年11月30日
	 * @param  @param form
	 * @param  @return
	 */
	@RequestMapping("/getHospOderInfoOld")
	@ResponseBody
	public Pagination getHospOderInfoOld(OrderPackage orderPackage){
		log.info("[医疗机构]获取完成订单数据："+orderPackage);
		Pagination page = new Pagination(request);
		try {
			HospInfo hosp = getUser().getInfo();
			orderPackage.setHospCode(hosp.getHospCode());
			page.setForm(orderPackage);
			page = purOrderInfoManager.getHospOderInfoOld(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	
	/**
	 * @category 跳向历史订单详情页面（医疗机构端）
	 * @Auther 徐国鹏
	 * @date 2015年7月30日 下午1:26:53
	 * @return String
	 */
	@RequestMapping("/toHospOderOldDateil")
	public String toHospOderOldDateil(){
		return "/trading/pur/hospOrderOldDateil";
	}
	/**
	 * 
	 *@category 获取订单信息详情列表数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午10:10:41
	 *@return
	 */
	@RequestMapping("/getHospOderOldDetail")
	@ResponseBody
	public Pagination getHospOderOldDetail(PurOrderInfoForm form){
		Pagination page = new Pagination(request);
		page.setForm(form);
		page = purOrderInfoManager.getHospOderOldDetail(page);
		return page;
	}	
	
	/**
	 * 
	 *@category 跳物流信息页面
	 *@author wangbing
	 *@date 2015年8月7日 下午14:50:08
	 *@return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/toOrderLogisticsInfo")
	public String toOrderLogisticsInfo(){
		String id = request.getParameter("interflowId");
		List<Map<String,Object>> list =  purOrderInfoManager.getPurOrderlogisticsById(id);
		Map<String,Object> form = purOrderInfoManager.getTheTimesById(id);
		List<Map<String,Object>> goodsInfo =  (List<Map<String, Object>>) purOrderInfoManager.getGoodInfoById(id);
		request.setAttribute("form", form);
		request.setAttribute("rows", list);
		request.setAttribute("goodsInfo", goodsInfo);
		return "/trading/pur/purOrderlogistics";
	}
	
	/**
	 * 
	 *@category 审核已提交的订单（医疗机构）
	 *@author 应晓川
	 *@date 2015年12月4日10:21:21
	 *@return
	 */
	@RequestMapping("/toAuditHospOderInfo")
	public String toAuditHospOderInfo(){
		//是否给出备案金额提示
		request.setAttribute("isHisRecordAmount", isHisRecordAmount);
		return "/trading/pur/auditHospOderInfo";
	}
	
	
	/**
	 * 
	 *@category 获取订单信息列表数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月10日 上午10:10:41
	 *@return
	 */
	@RequestMapping("/getNotAuditHospOderList")
	@ResponseBody
	public Pagination getNotAuditHospOderList(OrderPackage orderPackage){
			log.info("[医疗机构]获取订单信息列表数据："+orderPackage);
			Pagination page = new Pagination(request);
			try {
				HospInfo hosp = getUser().getInfo();
				orderPackage.setHospCode(hosp.getHospCode());
				page.setForm(orderPackage);
				page = purOrderInfoManager.getNotAuditHospOderList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
			}
			return page;
	}
	
	/**
	 * 
	 *@category 订单审核（医疗机构）
	 *@author 应晓川
	 *@date 2015年12月4日11:05:37
	 *@return
	 */
	@RequestMapping(value = {"/pass", "/notPass"})
	@ResponseBody
	public Pagination auditHospOderInfo(String state,String param,String baseAllAmount,String nonBaseAllAmount ,String allAmount ){
		log.info("[医疗机构]订单审核状态: "+state+" 参数： "+param+" 备案药物金额： "+baseAllAmount+" 非备案药物金额： "+nonBaseAllAmount+" 药物采购总金额： "+allAmount);
		Pagination page = new Pagination(request);
		page.getConditions().put("state", state);
		page.getConditions().put("param", param);
		Object obj= purOrderInfoManager.checkAuditHospOder(page);
		if(null!=obj){
			int count =Integer.parseInt(obj.toString());
			if(count!=param.split(",").length){
				page.setSuccess(false);
				page.setMsg("重复操作，请重新审核!");
				return page;
			}
		}
		page.setForm(getUser());
		page.getConditions().put("nonBaseAllAmount", nonBaseAllAmount);
		page.getConditions().put("baseAllAmount", baseAllAmount);
		page.getConditions().put("allAmount", allAmount);
		purOrderInfoManager.auditHospOderInfo(page);
		page.setSuccess(true);
		return page;
	}	
	/**
	 * @category 通过审核订单列表进入订单详细列表页面
	 * @date 2015年7月13日
	 * @return
	 */
	@RequestMapping("/toOrderDetailByAudit")
	public String toOrderDetailByAudit(Model model, String orderPackId) {
		Map<String, Object> map = orderConfirmManager.getOrderPackageById(orderPackId);
		model.addAttribute("orderPackId", orderPackId);
		model.addAttribute("orderPack", map);
		return "/trading/pur/orderDetailByAudit";
	}
	
	
	
	/**
	 * 
	 *@category 审核已提交的订单（医疗机构）
	 *@author 应晓川
	 *@date 2015年12月4日10:21:21
	 *@return
	 */
	@RequestMapping("/toAuditHospOderInfoResult")
	public String toAuditHospOderInfoResult(){
		return "/trading/pur/auditHospOderInfoResult";
	}
	@RequestMapping("/getAuditHospOderResultList")
	@ResponseBody
	public Pagination getAuditHospOderResultList(OrderPackage orderPackage){
			log.info("enter getAuditHospOderResultList method");
			Pagination page = new Pagination(request);
			try {
				HospInfo hosp = getUser().getInfo();
				orderPackage.setHospCode(hosp.getHospCode());
				page.setForm(orderPackage);
				page = purOrderInfoManager.getAuditHospOderResultList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
			}
			return page;
	}
	
	@RequestMapping("/checkHisRecordAmount")
	@ResponseBody
	public Pagination checkHisRecordAmount(String param){
			log.info("enter checkHisRecordAmount method");
			Pagination page = new Pagination(request);
			try {
				if(StringUtils.isNotBlank(param)){
					page.getConditions().put("param",param);
				}
				HospInfo hosp = getUser().getInfo();
				page.getConditions().put("hospCode", hosp.getHospCode());
				if(null != purOrderInfoManager.checkHisRecordAmount(page)){
					page.setSuccess(true);
				}else{
					page.setMsg("");
					page.setSuccess(false);	
				}
				
			} catch (Exception e) {
				log.error("",e);
			}
			return page;
	}
	@RequestMapping("/exportExcelByOrderDetail")
	@ResponseBody
	public Pagination exportExcelByOrderDetail(HttpServletResponse response) {
		
		Pagination page = new Pagination(request);
		DbUtil.jsonToMap(request, page);
		
		try {
			String title = "订单包号："+request.getParameter("orderPackId")+"明细";
			page.getConditions().put("NoPage", "1");
			OrderPackage orderPackage = new OrderPackage();
//			orderPackage.setOrderStatus(OrderPackStatus.confirmed.getKey());
//			StdCompinfo comp = getUser().getInfo();
//			orderPackage.setDelCompId(comp.getCompId());
			orderPackage.setDrugCode(request.getParameter("drugCode"));
			orderPackage.setDrugName(request.getParameter("drugName"));
			orderPackage.setCompName(request.getParameter("compName"));
			orderPackage.setOrderPackId(request.getParameter("orderPackId"));
			
			title = ExcelUtil.processFileName(request, title);  
			response.addHeader("Content-Disposition", "attachment;filename="+title+".xls");
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			
			page = orderConfirmManager.getOrderConfirmDetail(orderPackage, page);
			String[] headers = {"采购价","采购数量","到货数量","采购金额","通用名","剂型","规格","转换系数","单位","生产企业", "状态","缺货原因"};
			String[] alias = {"proPrice","proCount","recpCount","orderMoney","drugName","formName","specName","factor","unitName", "prodCompname", "orderStatus","confirmRemark"};
			String flag = request.getParameter("flag");
			ExcelUtil.exportExcel(page, os, flag.equals("1")?"未完成订单明细":flag.equals("2")?"已完成订单明细":"订单明细", headers, alias);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	
	
}